package com.artfii.fluentsql.example;

import com.artfii.fluentsql.core.jdbc.ConnectionBuilder;
import com.artfii.fluentsql.core.jdbc.ConnectionProvider;
import com.artfii.fluentsql.core.jdbc.FluentConnection;
import com.artfii.fluentsql.core.jdbc.FluentSqlConfig;
import com.artfii.fluentsql.core.tools.PropUtil;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;

/**
 * 集成到spring-booot
 */
@Configuration
@EnableTransactionManagement
public class ConnectionBuilderImpl implements ConnectionBuilder {

    private String env;
    private DataSource dataSource;
    private FluentSqlConfig config;
    private FluentConnection fluentConnection;
    @Resource
    private SpringConnectionProvider springConnectionProvider;

    public ConnectionBuilderImpl() {
        if (null == env) {
            this.env = PropUtil.getDefEnv();
        }
        if (null == config) {
            config = new FluentSqlConfig().build(this.env);
        }
    }

    @Bean("dataSource")
    public DataSource dataSource() {
        if (null == dataSource) {
            dataSource = config.getMasterDs();
        }
        return dataSource;
    }

    /**
     * 使用默认的事务名称（transactionManager）,如果你的事务名称不同，请自行修改
     * @return
     */
    @Bean("transactionManager")
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean("fluentConnection")
    @Primary
    public FluentConnection fluentConnection() {
        fluentConnection = buildConnection(springConnectionProvider,config).getConnectionOfPool(false);
        return fluentConnection;
    }

    public FluentConnection buildConnection(ConnectionProvider provider, FluentSqlConfig config) {
        fluentConnection = new FluentConnection(provider,config);
        return fluentConnection;
    }


    @Bean("jdbcTemplate")
    public JdbcTemplate jdbcTemplate(){
        return new JdbcTemplate(dataSource());
    }

    @Bean("namedParameterJdbcTemplate")
    public NamedParameterJdbcTemplate namedParameterJdbcTemplate(){
        return new NamedParameterJdbcTemplate(dataSource());
    }



}


